package com.example.photo_sharing.page.others;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.NetworkOnMainThreadException;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.photo_sharing.R;
import com.example.photo_sharing.global.App;
import com.example.photo_sharing.page.adapter.listSavesAdapter;
import com.example.photo_sharing.tool.Impl.EditImpl;
import com.example.photo_sharing.tool.Impl.UserInfoSPImpl;
import com.example.photo_sharing.entity.FindList;
import com.example.photo_sharing.entity.FindListItem;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class L_saves extends AppCompatActivity {


    private App app;
    private FindList fl = new FindList();

    private RecyclerView recyclerView; //定义ReclerView控件
    private ArrayList<FindListItem> goodsEntities = new ArrayList<>();
    private listSavesAdapter myadpater;
    private SwipeRefreshLayout swipeRefreshLayout;

    private String userId;
    private boolean sign_of_empty = true;

    private SharedPreferences sharedPreferences;
    private UserInfoSPImpl usp;

    private EditImpl edit;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        app = (App)getApplication();
        edit = new EditImpl();
        sharedPreferences = getSharedPreferences("userInfo",MODE_PRIVATE);
        usp = new UserInfoSPImpl(sharedPreferences);

        userId = usp.getUserId();

        get();
        app.setDelay(300);

        super.onCreate(savedInstanceState);

        setContentView(R.layout.navigation_find);

        //隐藏标题栏
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide(); //隐藏标题栏
        }


//        swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.find_refresh);
//
//        handleDownPullUpdate();
//
//        handleUpLoadMore();

        initRecyclerView();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void get(){
        new Thread(() -> {
            // url路径
            String url = "http://47.107.52.7:88/member/photo/share/save?"
                    +"current="+app.getCurrent()
                    +"&size="+app.getSize()
                    +"&userId="+userId;

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("Accept", "application/json, text/plain, */*")
                    .add("appId", app.getAppId())
                    .add("appSecret", app.getAppSecret())
                    .build();

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .get()
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }


    /**
     * 回调
     */
    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            String responseData = response.body().string();

            System.out.println(responseData);

            JSONObject jsonObject  = JSONObject.parseObject(responseData).getObject("data", JSONObject.class);

            if(jsonObject == null){
                return;
            }
            else{
                sign_of_empty = false;
            }

            JSONArray jsonArray = jsonObject.getJSONArray("records");

            fl.setCurrent(jsonObject.getInteger("total"));
            fl.setSize(jsonObject.getInteger("size"));
            fl.setTotal(jsonObject.getInteger("current"));

            //将获取的图片链接存入数据中
            ArrayList<FindListItem> fli = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject object = jsonArray.getJSONObject(i);
                FindListItem jo = JSON.toJavaObject(object,FindListItem.class);
                JSONArray ja = object.getJSONArray("imageUrlList");
                List<String> img_url = ja.toJavaList(String.class);
                jo.setImageUrlList(img_url);
                fli.add(i,jo);
            }
            fl.setRecords(fli);
            goodsEntities = fli;
            System.out.println(goodsEntities.size());
            System.out.println("成功");
        }
    };

    private void initRecyclerView() {
        recyclerView = (RecyclerView)findViewById(R.id.find_recyclerview);
        myadpater = new listSavesAdapter(this,goodsEntities);
        recyclerView.setAdapter(myadpater);
        recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));

        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));

        myadpater.setOnItemClickListener(new listSavesAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, FindListItem data)
            {
                //跳转到编辑页面
                Intent intent = new Intent(L_saves.this, Edit.class);
                intent.putStringArrayListExtra("urls",(ArrayList<String>) data.getImageUrlList());
                intent.putExtra("data",data);
                intent.putExtra("signOfOld",true);
                startActivity(intent);
            }

            @Override
            public void OnDeleteClick(View view,int pos,FindListItem data) {
                //删除并且刷新
                System.out.println("asdasdasd----------");
                edit.editDelete(userId,data.getId());
                app.setDelay(300);
                get();
                app.setDelay(300);
                initRecyclerView();
                Toast.makeText(L_saves.this,"删除成功",Toast.LENGTH_LONG).show();
            }

            @Override
            public void OnSendClick(View view, int position, FindListItem data) {
                //发布并且刷新
                System.out.println("asdasdasd----------");
                edit.editChange(data.getContent(),data.getTitle(),userId,data.getImageCode(),data.getId());
                app.setDelay(300);
                get();
                app.setDelay(300);
                initRecyclerView();
                Toast.makeText(L_saves.this,"发布成功",Toast.LENGTH_LONG).show();
            }
        });
    }

    private void handleDownPullUpdate() {
        swipeRefreshLayout.setEnabled(true);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                get();
                app.setDelay(300);
                initRecyclerView();

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //System.out.println("running");
                        swipeRefreshLayout.setRefreshing(false);
                    }
                },1000);
            }
        });
        //System.out.println("success");
    }

    /**
     * 添加十条数据
     * */
    private void addRecyclerData(){

    }

    private void handleUpLoadMore() {
        //加载显示，避免重复加载
        boolean load = true;

        LinearLayoutManager layoutManager;
        layoutManager = new LinearLayoutManager(this);

        recyclerView = (RecyclerView)findViewById(R.id.find_recyclerview);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            /**
             * 当 RecyclerView 的滚动状态改变时调用的回调方法。
             * 参数：
             * recyclerView – 滚动状态已更改的 RecyclerView。
             * newState – 更新的滚动状态。 SCROLL_STATE_IDLE 、 SCROLL_STATE_DRAGGING或SCROLL_STATE_SETTLING 。
             * */
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            /**
             * 当 RecyclerView 滚动时调用的回调方法。 这将在滚动完成后调用。
             * 如果在布局计算后可见项目范围发生变化，也会调用此回调。 在这种情况下，dx 和 dy 将为 0。
             * */
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //当dy为负时是往上   正才是往下
                if (dy > 0) {
                    int visibleItemCount = layoutManager.getChildCount();    //得到显示屏幕内的list数量
                    int totalItemCount = layoutManager.getItemCount();    //得到list的总数量
                    int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();//得到显示屏内的第一个list的位置数position
                    System.out.println("122222222222222"+" "+visibleItemCount+" "+totalItemCount+" "+firstVisiblePosition);
                    if (load && (visibleItemCount + firstVisiblePosition) >= totalItemCount) {
                        //添加数据，或者用网络请求
                        //记住加载完成后需要 load = false 无论成功与否
                        addRecyclerData();
                    }
                }
            }
        });
    }
}
